package com.ganzi.manager.exception;

import com.ganzi.manager.base.BaseException;
import com.ganzi.manager.base.BaseResponse;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.authz.UnauthorizedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;

/**
 * 全局异常拦截处理
 */
@ControllerAdvice("com.ganzi")
@ResponseBody
public class GlobalExceptionHandler {
    private Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(UnauthenticatedException.class)
    public BaseResponse unauthenticatedException(HttpServletResponse response, UnauthenticatedException ex) {
        logger.error(ex.getMessage(), ex);
        response.setStatus(500);
        return new BaseResponse(1000001, "未登录");
    }
    @ExceptionHandler(UnauthorizedException.class)
    public BaseResponse unauthorizedException(HttpServletResponse response, UnauthorizedException ex) {
        logger.error(ex.getMessage(), ex);
        response.setStatus(500);
        return new BaseResponse(1000002, "用户无权限");
    }

    @ExceptionHandler(BaseException.class)
    public BaseResponse baseExceptionHandler(HttpServletResponse response, BaseException ex) {
        logger.error(ex.getMessage(), ex);
        response.setStatus(500);
        return new BaseResponse(ex.getStatus(), ex.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public BaseResponse otherExceptionHandler(HttpServletResponse response, Exception ex) {
        response.setStatus(500);
        logger.error(ex.getMessage(), ex);
        return new BaseResponse(500, ex.getMessage());
    }

}
